package de.tu_darmstadt.informatik.tk.lernsystem.util;

import javax.jms.Connection;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * Not used.
 * Intended to be a backend for ActiveMQ/JMS.
 */
public class Notifications implements MessageListener, ExceptionListener {
	protected Connection connection = null;
	protected Session session = null;
	protected Topic destination = null;
	protected MessageConsumer consumer = null;
	protected MessageProducer producer = null;
	
	public void connect() throws JMSException {
		ActiveMQConnectionFactory connectionFactory = null;
		
		// Prepare ActiveMQ connection factory
		connectionFactory = new ActiveMQConnectionFactory("user", "pass", "broker");
		
		// Prepare connection			
		this.connection = connectionFactory.createConnection();
		this.connection.setExceptionListener(this);
		this.connection.start();
		
		// Prepare session and destination
		this.session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
		this.destination = this.session.createTopic("topic");
		
		// Prepare consumer
		this.consumer = this.session.createConsumer(this.destination);
		this.consumer.setMessageListener(this);
		
		// Prepare producer
		this.producer = this.session.createProducer(this.destination);
	}
	
	public MapMessage createMapMessage() throws JMSException {
		return session.createMapMessage();
	}
	
	public void sendMessage(Message msg) throws JMSException {
		// Send message via producer
		this.producer.send(msg);
	}
	
	public void disconnect() throws JMSException {
		// Close the producer
		this.producer.close();
		this.producer = null;
		
		// Close the consumer
		this.consumer.close();
		this.consumer = null;
		
		this.destination = null;
		
		// Close the session
		this.session.close();
		this.session = null;
		
		// Stop the connection
		this.connection.stop();
		this.connection.close();
		this.connection = null;
	}
	
	public Message receive(long timeout) throws JMSException {
		return this.consumer.receive(timeout);
	}
		
	public void onMessage(Message message) {
		System.out.println(message);
	}
	
	public void onException(JMSException exception) {
		exception.printStackTrace();
	}
}
